<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true">
      <el-form-item label="流程实例ID：" prop="instanceId">
        <el-input
          v-model="queryParams.instanceId"
          placeholder
          clearable
          size="small"
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" :data="taskList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="标题" prop="title" min-width="6%" />
      <el-table-column label="原因" prop="reason" min-width="6%" />
      <el-table-column label="开始时间" prop="startTime" min-width="14%">
        <template slot-scope="scope">
          <span>{{moment(scope.row.startTime).format('YYYY-MM-DD HH:mm:ss')}}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束时间" prop="endTime" min-width="14%">
        <template slot-scope="scope">
          <span>{{moment(scope.row.endTime).format('YYYY-MM-DD HH:mm:ss')}}</span>
        </template>
      </el-table-column>
      <el-table-column label="请假时长" prop="totalTime" min-width="15%">
        <template slot-scope="scope">
          <span>{{formatTotalDateSub(scope.row.totalTime)}}</span>
        </template>
      </el-table-column>
      <el-table-column label="流程实例ID" prop="instanceId" min-width="8%" />
      <el-table-column label="申请人" min-width="8%">
        <template slot-scope="scope">
          <span style="color:#F00; font-weight:bold">{{ scope.row.applyUserName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="申请时间" prop="applyTime" min-width="14%">
        <template slot-scope="scope">
          <span>{{moment(scope.row.applyTime).format('YYYY-MM-DD HH:mm:ss')}}</span>
        </template>
      </el-table-column>
      <el-table-column label="当前任务名称" min-width="10%">
        <template slot-scope="scope">
          <span style="color:#F00; font-weight:bold">{{ scope.row.taskName }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        min-width="50%"
      >
        <template slot-scope="scope">
          <el-button
            el-if="scope.row.taskName.indexOf('已挂起') === -1"
            size="small"
            round
            type="primary"
            icon="el-icon-edit"
            @click="handleApproval(scope.row)"
          >{{ scope.row.taskName }}</el-button>
          <el-button
            size="small"
            type="warning"
            round
            icon="el-icon-circle-check"
            @click="handleApplyDetail(scope.row)"
          >申请详情</el-button>
          <el-button
            size="small"
            type="danger"
            round
            icon="el-icon-document"
            @click="handleHistory(scope.row)"
          >审批历史</el-button>
          <el-button
            size="small"
            type="success"
            round
            icon="el-icon-user"
            @click="handleView(scope.row)"
          >进度查看</el-button>
          <el-button
            el-if="scope.row.taskName.indexOf('已挂起') === -1"
            size="small"
            round
            type="info"
            icon="el-icon-news"
            @click="handleDelegat(scope.row)"
          >委托</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 审批弹窗 -->
    <el-dialog
      :visible.sync="dialogParams.tdlvOpen"
      :title="dialogParams.tdlvTitle"
      width="600px"
      append-to-body
    >
      <el-form ref="form" :model="taskVerify" label-width="90px">
        <el-form-item label="申请人：">
          <el-input v-model="taskVerify.applyUserName" placeholder :readonly="true" />
        </el-form-item>
        <el-form-item label="结束时间: ">
          <el-date-picker
            clearable
            size="small"
            style="width: 200px"
            :readonly="true"
            v-model="taskVerify.endTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="标题：">
          <el-input v-model="taskVerify.title" placeholder :readonly="true" />
        </el-form-item>
        <el-form-item label="原因：">
          <el-input v-model="taskVerify.reason" placeholder :readonly="true" />
        </el-form-item>
        <el-form-item label="开始时间: ">
          <el-date-picker
            clearable
            size="small"
            style="width: 200px"
            :readonly="true"
            v-model="taskVerify.startTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择开始时间"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间: ">
          <el-date-picker
            clearable
            size="small"
            style="width: 200px"
            :readonly="true"
            v-model="taskVerify.endTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择结束时间"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="请假时长: ">
          <el-input v-model="totalTime.approvalTotalTime" placeholder :readonly="true" />
        </el-form-item>

        <el-form-item label="审批意见：">
          <div class="type-select" v-if="taskVerify.taskName=='部门领导审批'">
            <select v-model="taskVerify.deptLeaderApproved">
              <option value="true" default>同意</option>
              <option value="false">拒绝</option>
            </select>
          </div>
          <div class="type-select" v-if="taskVerify.taskName=='人事审批'">
            <select v-model="taskVerify.hrApproved">
              <option value="true" default>同意</option>
              <option value="false">拒绝</option>
            </select>
          </div>
          <div class="type-select" v-if="taskVerify.taskName=='调整申请'">
            <select v-model="taskVerify.reApply">
              <option value="true" default>重新申请</option>
              <option value="false">结束流程</option>
            </select>
          </div>
          <div class="type-select" v-if="taskVerify.taskName=='销假'">
            <el-input placeholder :readonly="true" />
          </div>
        </el-form-item>
        <el-form-item label="批注：">
          <el-input
            type="textarea"
            v-model="taskVerify.comment"
            placeholder
            clearable
            size="small"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitLeaveForm(taskVerify)">确 定</el-button>
        <el-button @click="dialogParams.tdlvOpen = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 委托弹窗 -->
    <el-dialog
      :visible.sync="dialogParams.delegatOpen"
      :title="dialogParams.delegatTitle"
      width="800px"
      append-to-body
    >
      <el-form :model="userListQueryParams" ref="queryForm" :inline="true">
        <el-form-item label="用户名称: " prop="first">
          <el-input
            v-model="userListQueryParams.first"
            placeholder
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="手机号码: " prop="phoneNumber">
          <el-input
            v-model="userListQueryParams.phoneNumber"
            placeholder
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <el-table
        v-loading="userLoading"
        :data="processUserList"
        @selection-change="handleSelectionDelegatChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="用户名称" align="center" prop="first" min-width="12%" />
        <el-table-column label="邮箱" align="center" prop="email" min-width="12%" />
      </el-table>

      <pagination
        v-show="userTotal>0"
        :total="userTotal"
        :page.sync="userListQueryParams.pageNum"
        :limit.sync="userListQueryParams.pageSize"
        @pagination="getUserList"
      />
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitDelegat()">确 定</el-button>
        <el-button @click="delegatDialogCancle()">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 申请详情弹出层 -->
    <el-dialog
      :visible.sync="dialogParams.detailOpen"
      :title="dialogParams.detailTitle"
      width="600px"
      append-to-body
    >
      <el-form ref="form" :model="formData" label-width="90px">
        <el-form-item label="申请人：">
          <el-input v-model="formData.applyUserName" placeholder :readonly="true" />
        </el-form-item>
        <el-form-item label="申请时间: ">
          <el-date-picker
            clearable
            size="small"
            style="width: 200px"
            :readonly="true"
            v-model="formData.applyTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="标题：">
          <el-input v-model="formData.title" placeholder :readonly="true" />
        </el-form-item>
        <el-form-item label="原因：">
          <el-input v-model="formData.reason" placeholder :readonly="true" />
        </el-form-item>
        <el-form-item label="开始时间: ">
          <el-date-picker
            clearable
            size="small"
            style="width: 200px"
            :readonly="true"
            v-model="formData.startTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择开始时间"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间: ">
          <el-date-picker
            clearable
            size="small"
            style="width: 200px"
            :readonly="true"
            v-model="formData.endTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择结束时间"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="请假时长: ">
          <el-input v-model="totalTime.detailTotalTime" placeholder :readonly="true" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogParams.detailOpen = false">关闭</el-button>
      </div>
    </el-dialog>

    <!-- 审批历史对话框  -->
    <el-dialog
      :visible.sync="dialogParams.historyOpen"
      :title="dialogParams.historyTitle"
      width="900px"
      append-to-body
    >
      <el-form :model="historyQueryParams" ref="queryForm" :inline="true">
        <el-form-item label="任务名称: " prop="activityName">
          <el-input
            v-model="historyQueryParams.activityName"
            placeholder="请输入任务名称"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="办理人ID: " prop="assignee">
          <el-input
            v-model="historyQueryParams.assignee"
            placeholder="请输入办理人ID"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <el-table v-loading="historyLoading" :data="historyList">
        <el-table-column label="任务名称" align="center" prop="activityName" min-width="12%" />
        <el-table-column label="办理人" align="center" prop="assigneeName" min-width="12%" />
        <el-table-column label="审批意见" align="center" prop="comment" min-width="12%" />
        <el-table-column label="开始时间" align="center" prop="startTime" min-width="15%">
          <template slot-scope="scope">
            <span>{{ moment(scope.row.startTime).format('YYYY-MM-DD HH:mm:ss') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="结束时间" align="center" prop="endTime" min-width="15%">
          <template slot-scope="scope">
            <span>{{ moment(scope.row.endTime).format('YYYY-MM-DD HH:mm:ss') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="耗时" align="center" prop="durationInMillis" min-width="15%">
          <template slot-scope="scope">
            <span>{{ formatTotalDateSub(scope.row.durationInMillis/1000) }}</span>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="historyListTotal>0"
        :total="historyListTotal"
        :page.sync="historyQueryParams.pageNum"
        :limit.sync="historyQueryParams.pageSize"
        @pagination="getHistoryList"
      />
    </el-dialog>

    <el-dialog
      :visible.sync="dialogParams.readResourceOpen"
      :title="dialogParams.readResourceTitle"
      width="800px"
      append-to-body
    >
      <div>
        <el-image />
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  taskListLeave,
  approvalLeave,
  deleget
} from "@/api/process/leave/leave";
import { listHistory } from "@/api/process/processMenu/definition";
import { listProcessUser } from "@/api/process/processMenu/processUser";
import { getToken } from "@/utils/auth";
import axios from "axios";
import Qs from "qs";

export default {
  name: "LeaveTodo",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 任务表格数据
      taskList: [],
      // 用户表格数据
      processUserList: [],
      // 审批历史表格数据
      historyList: [],
      historyLoading: true,
      historyListTotal: 0,
      // 申请详情
      formData: {},
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        instanceId: undefined
      },
      // 审批历史查询参数
      historyQueryParams: {
        pageNum: 1,
        pageSize: 10,
        activityName: undefined,
        assign: undefined
      },
      // 用户查询参数
      userListQueryParams: {
        pageNum: 1,
        pageSize: 10,
        first: undefined,
        phoneNumber: ""
      },
      userLoading: true,
      userTotal: 0,
      // 审核参数
      taskVerify: {
        totalTime: undefined,
        comment: undefined,
        deptLeaderApproved: undefined,
        hrApproved: undefined,
        reApply: undefined
      },
      totalTime: {
        approvalTotalTime: undefined,
        detailTotalTime: undefined
      },
      // 弹窗参数
      dialogParams: {
        tdlvOpen: false,
        tdlvTitle: "",
        delegatOpen: false,
        delegatTitle: "",
        detailOpen: false,
        delegatTitle: "",
        historyOpen: false,
        historyTitle: "",
        taskId: "",
        delegateToUser: ""
      },
      // 表单参数
      form: {},
      defaultProps: {
        children: "children",
        label: "label"
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    // 计算时间差,单位: 秒
    calcTotalSecond(startDateStr, endDateStr) {
      var date1 = new Date(startDateStr); // 开始时间
      var date2 = new Date(endDateStr); // 结束时间
      var timeSub = date2.getTime() - date1.getTime(); // 时间差毫秒
      return timeSub / 1000;
    },

    // 计算时间差，单位: xx天xx时xx分xx秒
    formatTotalDateSub(row, column) {
      let secondSub = row;
      var days = Math.floor(secondSub / (24 * 3600)); // 计算出小时数
      var leave1 = secondSub % (24 * 3600); // 计算天数后剩余的毫秒数
      var hours = Math.floor(leave1 / 3600); // 计算相差分钟数
      var leave2 = leave1 % 3600; // 计算小时数后剩余的毫秒数
      var minutes = Math.floor(leave2 / 60); // 计算相差秒数
      var leave3 = leave2 % 60; // 计算分钟数后剩余的毫秒数
      var seconds = Math.round(leave3);
      return (
        days + " 天 " + hours + " 时 " + minutes + " 分 " + seconds + " 秒"
      );
    },

    /** 查询请假列表 */
    getList() {
      this.loading = true;
      taskListLeave(this.queryParams).then(response => {
        this.taskList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询用户列表 */
    getUserList() {
      this.userLoading = true;
      listProcessUser(this.userListQueryParams).then(response => {
        this.processUserList = response.rows;
        this.userTotal = response.total;
        this.userLoading = false;
      });
    },

    /** 查询历史审核列表 */
    getHistoryList(row) {
      this.historyLoading = true;
      var params = new URLSearchParams();
      params.append("instanceId", row.instanceId);
      listHistory(params)
        .then(response => {
          this.historyList = response.rows;
          this.historyListTotal = response.total;
          this.historyLoading = false;
        })
        .catch(function() {});
    },

    /** 历史审批按钮操作 */
    handleHistory(row) {
      this.dialogParams.historyOpen = true;
      this.dialogParams.historyTitle = "查看历史审批";
      this.getHistoryList(row);
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },

    // 取消按钮
    cancel() {
      this.taskVerify.open = false;
      this.reset();
    },
    // 委托弹窗取消
    delegatDialogCancle() {
      this.dialogParams.delegatOpen = false;
      this.getList();
    },
    /** 委托按钮操作 */
    handleDelegat(row) {
      this.dialogParams.taskId = row.taskId;
      this.dialogParams.delegatOpen = true;
      this.dialogParams.delegatTitle = "关联系统用户";
      this.getUserList();
    },
    /** 委托提交按钮操作 */
    submitDelegat() {
      let params = new URLSearchParams();
      params.append("taskId", this.dialogParams.taskId);
      params.append("delegateToUser", this.dialogParams.delegateToUser);
      deleget(params)
        .then(response => {
          this.dialogParams.delegatOpen = false;
          this.getList();
          if (response.code == 0) {
            this.msgSuccess(response.msg);
          }
        })
        .catch(function() {});
    },
    /** 审批按钮操作 */
    handleApproval(row) {
      this.totalTime.approvalTotalTime = this.formatTotalDateSub(row.totalTime);
      this.taskVerify = row;
      this.dialogParams.tdlvOpen = true;
      this.dialogParams.tdlvTitle = "部门领导审批";
    },
    /** 申请详情按钮操作 */
    handleApplyDetail(row) {
      this.totalTime.detailTotalTime = this.formatTotalDateSub(row.totalTime);
      this.formData = row;
      this.dialogParams.detailOpen = true;
      this.dialogParams.detailTitle = "申请详情";
    },

    // 审批提交按钮
    submitLeaveForm(params) {
      let id = params.taskId;
      let data = {
        id: params.id,
        p_COM_comment: "",
        applyUserName: params.applyUserName,
        title: params.title,
        reason: params.reason,
        totalTime: params.totalTime,
        totalTimeText: params.totalTimeText,
        p_B_deptLeaderApproved: this.taskVerify.deptLeaderApproved,
        p_B_hrApproved: this.taskVerify.hrApproved,
        p_B_reApply: this.taskVerify.reApply,
        comment: this.taskVerify.comment
      };
      axios({
        headers: {
          Authorization: "Bearer " + getToken(),
          "Content-Type": "application/x-www-form-urlencoded"
        },
        method: "post",
        url: process.env.VUE_APP_BASE_API + "/activiti/leave/complete/" + id,
        data: Qs.stringify(data)
      }).then(res => {
        this.getList();
        this.dialogParams.tdlvOpen = false;
        if (res.data.code == 0) {
          this.msgSuccess(res.data.msg);
        } else {
          this.msgError(res.data.msg);
        }
      });
    },

    // 多选框选中数据
    handleSelectionDelegatChange(selection) {
      this.dialogParams.delegateToUser = selection.map(item => item.first);
    }
  }
};
</script>